import {
	TilesRenderer,
	NONE,
	SCREEN_ERROR,
	GEOMETRIC_ERROR,
	DISTANCE,
	DEPTH,
	RELATIVE_DEPTH,
	IS_LEAF,
	RANDOM_COLOR,
	RANDOM_NODE_COLOR,
	CUSTOM_COLOR,
	LOAD_ORDER,
} from '3d-tiles-renderer';
import {
	DebugTilesPlugin,
	ImplicitTilingPlugin,
	GLTFCesiumRTCExtension,
} from '3d-tiles-renderer/plugins';
import {
	Scene,
	DirectionalLight,
	AmbientLight,
	WebGLRenderer,
	PerspectiveCamera,
	CameraHelper,
	Box3,
	Raycaster,
	Vector2,
	Mesh,
	Sprite,
	Texture,
	SpriteMaterial,
	BoxGeometry,
	MeshPhongMaterial,
	CylinderGeometry,
	MeshBasicMaterial,
	Group,
	TorusGeometry,
	OrthographicCamera,
	Sphere,
	Color,
	SphereGeometry,
	Object3D,
	DoubleSide,
	MeshPhysicalMaterial,
	ShaderMaterial,
	MeshStandardMaterial,
	MeshNormalMaterial,
	BufferAttribute,
	BufferGeometry,
	LineSegments,
	LineBasicMaterial,
	EdgesGeometry
} from 'three';
import { FlyOrbitControls } from './FlyOrbitControls.js';
import * as BufferGeometryUtils from 'three/examples/jsm/utils/BufferGeometryUtils.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js';
import { KTX2Loader } from 'three/examples/jsm/loaders/KTX2Loader.js';
import { GUI } from 'three/examples/jsm/libs/lil-gui.module.min.js';
import Stats from 'three/examples/jsm/libs/stats.module.js';
import { createMultiMaterialObject } from 'three/examples/jsm/utils/SceneUtils.js';
import { addLoading, removeLoading } from "../threeRender/utils/loading";

const ALL_HITS = 1;
const FIRST_HIT_ONLY = 2;

const DEFAULT = 0;
const GRADIENT = 1;
const TOPOGRAPHIC_LINES = 2;
const LIGHTING = 3;
const GLASS = 4;

const hashUrl = window.location.hash.replace( /^#/, '' );
let camera, controls, scene, renderer, tiles, cameraHelper;
let thirdPersonCamera, thirdPersonRenderer, thirdPersonControls;
let secondRenderer, secondCameraHelper, secondControls, secondCamera;
let orthoCamera, orthoCameraHelper;
let box, sphere;
let raycaster, mouse, rayIntersect, lastHoveredElement;
let offsetParent, geospatialRotationParent;
let statsContainer, stats;
let tilesRendererArr = [];


const params = {

	enableUpdate: true,
	raycast: NONE,
	optimizeRaycast: true,
	enableCacheDisplay: false,
	enableRendererStats: false,
	orthographic: false,

	errorTarget: 6,
	errorThreshold: 60,
	maxDepth: 15,
	displayActiveTiles: false,
	resolutionScale: 1.0,

	up: hashUrl ? '+Z' : '+Y',
	//up: hashUrl ? '+Y' : '+Z',
	displayBoxBounds: false,
	displaySphereBounds: false,
	displayRegionBounds: false,
	colorMode: 0,
	showThirdPerson: false,
	showSecondView: false,
	material: DEFAULT,
	reload: reinstantiateTiles
};

const gradientShader = {
	vertexShader: /* glsl */`
		varying vec3 wPosition;
		void main() {

			#include <begin_vertex>
			#include <project_vertex>
			wPosition = ( modelMatrix * vec4( transformed, 1.0 ) ).xyz;

		}
	`,
	fragmentShader: /* glsl */`
		varying vec3 wPosition;
		void main() {

			float minVal = - 30.0;
			float maxVal = 30.0;

			float val = ( wPosition.y - minVal ) / ( maxVal - minVal );

			vec4 color1 = vec4( 0.149, 0.196, 0.219, 1.0 ) * 0.5;
			vec4 color2 = vec4( 1.0 );

			gl_FragColor = mix( color1, color2, val );

		}
	`,

};

const topoShader = {
	extensions: {
		derivatives: true,
	},
	vertexShader: /* glsl */`
		varying vec3 wPosition;
		varying vec3 vViewPosition;
		void main() {

			#include <begin_vertex>
			#include <project_vertex>
			wPosition = ( modelMatrix * vec4( transformed, 1.0 ) ).xyz;
			vViewPosition = - mvPosition.xyz;

		}
	`,
	fragmentShader: /* glsl */`
		varying vec3 wPosition;
		varying vec3 vViewPosition;
		void main() {

			// lighting
			vec3 fdx = vec3( dFdx( wPosition.x ), dFdx( wPosition.y ), dFdx( wPosition.z ) );
			vec3 fdy = vec3( dFdy( wPosition.x ), dFdy( wPosition.y ), dFdy( wPosition.z ) );
			vec3 worldNormal = normalize( cross( fdx, fdy ) );

			float lighting =
				0.4 +
				clamp( dot( worldNormal, vec3( 1.0, 1.0, 1.0 ) ), 0.0, 1.0 ) * 0.5 +
				clamp( dot( worldNormal, vec3( - 1.0, 1.0, - 1.0 ) ), 0.0, 1.0 ) * 0.3;

			// thickness scale
			float upwardness = dot( worldNormal, vec3( 0.0, 1.0, 0.0 ) );
			float yInv = saturate( 1.0 - abs( upwardness ) );
			float thicknessScale = pow( yInv, 0.4 );
			thicknessScale *= 0.25 + 0.5 * ( vViewPosition.z + 1.0 ) / 2.0;

			// thickness
			float thickness = 0.01 * thicknessScale;
			float thickness2 = thickness / 2.0;
			float m = mod( wPosition.y, 3.0 );

			// soften edge
			float center = thickness2;
			float dist = clamp( abs( m - thickness2 ) / thickness2, 0.0, 1.0 );

			vec4 topoColor = vec4( 0.149, 0.196, 0.219, 1.0 ) * 0.5;
			gl_FragColor = mix( topoColor * lighting, vec4( lighting ), dist );

		}
	`,

};

let wellItems = new Object3D();
let wellSprites = new Object3D();

// 井筒 WELL 数据 使用大地坐标时，XCOORD、YCOORD的值非常大
// 基准点坐标, 分别为XCOORD0和YCOORD0，XCOORD和YCOORD数组只记录偏移量。
// 基准XCOORD0 + 偏移XCOORD
// 基准YCOORD0 + 偏移YCOORD
let XCOORD0 = 630752.507
let YCOORD0 = 4338916.207 
let infoTIME = 0
/*
WELL 1 'GR1-1' 305 'SHUT'
WELL 2 'GR1-2' 370 'LRAT:999.9999 SM3/DAY'
WELL 3 'GR1-3' 370 'LRAT:999.9999 SM3/DAY'
WELL 4 'GR1-4' 371 'LRAT:999.9928 SM3/DAY'
WELL 5 'GR2-2' 355 'SHUT'
WELL 6 'GR2-3' 356 'LRAT:1000 SM3/DAY'
WELL 7 'GR2-4' 331 'LRAT:1000 SM3/DAY'
WELL 8 'GR2-5' 343 'LRAT:1000 SM3/DAY'
WELL 9 'GR3-2' 389 'LRAT:999.9997 SM3/DAY'
WELL 10 'GR3-3' 363 'SHUT'
WELL 11 'GR3-4' 365 'LRAT:1000 SM3/DAY'
WELL 12 'GR3-6' 363 'LRAT:1000 SM3/DAY'
WELL 13 'GR4-1' 370 'LRAT:999.9999 SM3/DAY'
WELL 14 'GR4-2' 347 'SHUT'
WELL 15 'GR4-3' 319 'LRAT:1000 SM3/DAY'
WELL 16 'GR4-4' 355 'LRAT:1000 SM3/DAY'
WELL 17 'GR4-5' 351 'LRAT:1000 SM3/DAY'
WELL 18 'GR4-6' 332 'LRAT:1000 SM3/DAY'
WELL 19 'GR5-1' 382 'LRAT:1000 SM3/DAY'
WELL 20 'GR5-2' 386 'LRAT:1000 SM3/DAY'
WELL 21 'GR5-5' 318 'SHUT'
WELL 22 'GR5-6' 392 'LRAT:1000 SM3/DAY'
WELL 23 'GR6-2' 357 'LRAT:1000 SM3/DAY'
WELL 24 'GR6-3' 312 'SHUT'
WELL 25 'GR6-4' 316 'LRAT:1000 SM3/DAY'
WELL 26 'GR6-5' 351 'LRAT:1000 SM3/DAY'
WELL 27 'GR7-2' 273 'SHUT'
WELL 28 'GR7-3' 195 'LRAT:999.9997 SM3/DAY'
*/

let wellInfo = [
	{
		id: '1',//井号
		name: 'GR1-1',//井名
		num: '305',//井节点数目
		cpr:'SHUT',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest 
				rest: [
					{key:'XCOORD',unit:'m',value: '1634.44'},
					{key:'YCOORD',unit:'m',value: '-513.6248'},
					{key:'DEPTH',unit:'m',value: '1852.081'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//井筒压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速 
					{key:'QO',unit:'m3/day',value: '0'},//油流速oil 正号为流入、负号为注入，均转化到地面状态的体积流速。
					{key:'QG',unit:'m3/day',value: '0'},//气流速gas 正号为流入、负号为注入，均转化到地面状态的体积流速。
					{key:'QW',unit:'m3/day',value: '0'},//水流速water 正号为流入、负号为注入，均转化到地面状态的体积流速。
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				]  
			}
		]
		
	},
	{
		id: '2',//井号
		name: 'GR1-2',//井名
		num: '370',//井节点数目
		cpr:'LRAT:999.9999 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '1578.101'},
					{key:'YCOORD',unit:'m',value: '-904.3235'},
					{key:'DEPTH',unit:'m',value: '1857.264'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				] 
			}
		]
		
	},
	{
		id: '3',//井号
		name: 'GR1-3',//井名
		num: '370',//井节点数目
		cpr:'LRAT:999.9999 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '2040.376'},
					{key:'YCOORD',unit:'m',value: '-613.6444'},
					{key:'DEPTH',unit:'m',value: '1884.242'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				] 
			}
		]
		
	},
	{
		id: '4',//井号
		name: 'GR1-4',//井名
		num: '371',//井节点数目
		cpr:'LRAT:999.9928 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '1266.302'},
					{key:'YCOORD',unit:'m',value: '-702.4572'},
					{key:'DEPTH',unit:'m',value: '1832.496'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				] 
			}
		]
		
	},
	{
		id: '5',//井号
		name: 'GR2-2',//井名
		num: '355',//井节点数目
		cpr:'SHUT',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '2321.342'},
					{key:'YCOORD',unit:'m',value: '-1500.041'},
					{key:'DEPTH',unit:'m',value: '1884.405'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				]  
			}
		]
		
	},
	{
		id: '6',//井号
		name: 'GR2-3',//井名
		num: '356',//井节点数目
		cpr:'LRAT:1000 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '2435.878'},
					{key:'YCOORD',unit:'m',value: '-1829.453'},
					{key:'DEPTH',unit:'m',value: '1880.274'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				]  
			}
		]
		
	},
	{
		id: '7',//井号
		name: 'GR2-4',//井名
		num: '331',//井节点数目
		cpr:'LRAT:1000 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '2541.56'},
					{key:'YCOORD',unit:'m',value: '-941.6433'},
					{key:'DEPTH',unit:'m',value: '1887.254'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				] 
			}
		]
		
	},
	{
		id: '8',//井号
		name: 'GR2-5',//井名
		num: '356',//井节点数目
		cpr:'LRAT:1000 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '2726.393'},
					{key:'YCOORD',unit:'m',value: '-1284.873'},
					{key:'DEPTH',unit:'m',value: '1900.401'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				]
			}
		]
		
	},
	{
		id: '9',//井号
		name: 'GR3-2',//井名
		num: '389',//井节点数目
		cpr:'LRAT:999.9997 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '2769.661'},
					{key:'YCOORD',unit:'m',value: '-1242.292'},
					{key:'DEPTH',unit:'m',value: '1901.514'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				] 
			}
		]
		
	},
	{
		id: '10',//井号
		name: 'GR3-3',//井名
		num: '363',//井节点数目
		cpr:'SHUT',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '3255.522'},
					{key:'YCOORD',unit:'m',value: '-1449.746'},
					{key:'DEPTH',unit:'m',value: '1889.97'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				] 
			}
		]
		
	},
	{
		id: '11',//井号
		name: 'GR3-4',//井名
		num: '365',//井节点数目
		cpr:'LRAT:1000 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '3354.514'},
					{key:'YCOORD',unit:'m',value: '-551.0424'},
					{key:'DEPTH',unit:'m',value: '1929.548'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				] 
			}
		]
		
	},
	{
		id: '12',//井号
		name: 'GR3-6',//井名
		num: '363',//井节点数目
		cpr:'LRAT:1000 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '3671.499'},
					{key:'YCOORD',unit:'m',value: '-1282.311'},
					{key:'DEPTH',unit:'m',value: '1925.202'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				]
			}
		]
		
	},
	{
		id: '13',//井号
		name: 'GR4-1',//井名
		num: '370',//井节点数目
		cpr:'LRAT:999.9999 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '3755.437'},
					{key:'YCOORD',unit:'m',value: '-344.6722'},
					{key:'DEPTH',unit:'m',value: '1960.381'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				]  
			}
		]
		
	},
	{
		id: '14',//井号
		name: 'GR4-2',//井名
		num: '347',//井节点数目
		cpr:'SHUT',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '3925.16'},
					{key:'YCOORD',unit:'m',value: '-686.4225'},
					{key:'DEPTH',unit:'m',value: '1963.771'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				]  
			}
		]
		
	},
	{
		id: '15',//井号
		name: 'GR4-3',//井名
		num: '319',//井节点数目
		cpr:'LRAT:1000 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '4098.873'},
					{key:'YCOORD',unit:'m',value: '-1049.915'},
					{key:'DEPTH',unit:'m',value: '1950.633'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				] 
			}
		]
		
	},
	{
		id: '16',//井号
		name: 'GR4-4',//井名
		num: '355',//井节点数目
		cpr:'LRAT:1000 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '4092.854'},
					{key:'YCOORD',unit:'m',value: '-166.9816'},
					{key:'DEPTH',unit:'m',value: '1984.752'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				]
			}
		]
		
	},
	{
		id: '17',//井号
		name: 'GR4-5',//井名
		num: '351',//井节点数目
		cpr:'LRAT:1000 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '4245.787'},
					{key:'YCOORD',unit:'m',value: '-516.7445'},
					{key:'DEPTH',unit:'m',value: '1989.236'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				]  
			}
		]
		
	},
	{
		id: '18',//井号
		name: 'GR4-6',//井名
		num: '332',//井节点数目
		cpr:'LRAT:1000 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '4504.464'},
					{key:'YCOORD',unit:'m',value: '-870.1137'},
					{key:'DEPTH',unit:'m',value: '1981.408'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				] 
			}
		]
		
	},
	{
		id: '19',//井号
		name: 'GR5-1',//井名
		num: '382',//井节点数目
		cpr:'LRAT:1000 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '3889.889'},
					{key:'YCOORD',unit:'m',value: '-1840.704'},
					{key:'DEPTH',unit:'m',value: '1912.83'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				]
			}
		]
		
	},
	{
		id: '20',//井号
		name: 'GR5-2',//井名
		num: '386',//井节点数目
		cpr:'LRAT:1000 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '3932.508'},
					{key:'YCOORD',unit:'m',value: '-2208.018'},
					{key:'DEPTH',unit:'m',value: '1909.972'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				]  
			}
		]
		
	},
	{
		id: '21',//井号
		name: 'GR5-5',//井名
		num: '318',//井节点数目
		cpr:'SHUT',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '4372.747'},
					{key:'YCOORD',unit:'m',value: '-1994.812'},
					{key:'DEPTH',unit:'m',value: '1920.678'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				] 
			}
		]
		
	},
	{
		id: '22',//井号
		name: 'GR5-6',//井名
		num: '392',//井节点数目
		cpr:'LRAT:1000 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '4591.463'},
					{key:'YCOORD',unit:'m',value: '-2394.178'},
					{key:'DEPTH',unit:'m',value: '1920.089'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				]  
			}
		]
		
	},
	{
		id: '23',//井号
		name: 'GR6-2',//井名
		num: '357',//井节点数目
		cpr:'LRAT:1000 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '4804.098'},
					{key:'YCOORD',unit:'m',value: '-267.5754'},
					{key:'DEPTH',unit:'m',value: '2016.597'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				]  
			}
		]
		
	},
	{
		id: '24',//井号
		name: 'GR6-3',//井名
		num: '312',//井节点数目
		cpr:'SHUT',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '4987.155'},
					{key:'YCOORD',unit:'m',value: '-626.5946'},
					{key:'DEPTH',unit:'m',value: '2020.773'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				]  
			}
		]
		
	},
	{
		id: '25',//井号
		name: 'GR6-4',//井名
		num: '316',//井节点数目
		cpr:'LRAT:1000 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '5130.427'},
					{key:'YCOORD',unit:'m',value: '-123.4141'},
					{key:'DEPTH',unit:'m',value: '2015.812'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				] 
			}
		]
		
	},
	{
		id: '26',//井号
		name: 'GR6-5',//井名
		num: '351',//井节点数目
		cpr:'LRAT:1000 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '5601.456'},
					{key:'YCOORD',unit:'m',value: '-789.9283'},
					{key:'DEPTH',unit:'m',value: '2018.281'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				]  
			}
		]
		
	},
	{
		id: '27',//井号
		name: 'GR7-2',//井名
		num: '273',//井节点数目
		cpr:'SHUT',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '5770.853'},
					{key:'YCOORD',unit:'m',value: '-271.2598'},
					{key:'DEPTH',unit:'m',value: '2032.128'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				] 
			}
		]
		
	},
	{
		id: '28',//井号
		name: 'GR7-3',//井名
		num: '195',//井节点数目
		cpr:'LRAT:999.9997 SM3/DAY',//当前生产制度
		time: '0',//数据时间
		data:[
			{
				// 静态数据 rest
				rest: [
					{key:'XCOORD',unit:'m',value: '5941.789'},
					{key:'YCOORD',unit:'m',value: '285.394'},
					{key:'DEPTH',unit:'m',value: '1992.729'},
					{key:'STAGE',unit:'integer',value: '0'},
					{key:'OUTLET',unit:'integer',value: '-1'},
				],
				//动态数据 motion
				motion: [
					{key:'WI',unit:'mD*m',value: '0'},//井筒内径
					{key:'PRES',unit:'bar',value: '186.7146'},//压力
					{key:'PCON',unit:'',value: '0'},//油
					{key:'VM',unit:'m/day',value: '61038.07'},//井筒流速
					{key:'QO',unit:'m3/day',value: '0'},//油oil
					{key:'QG',unit:'m3/day',value: '0'},//气gas
					{key:'QW',unit:'m3/day',value: '0'},//水water
					{key:'WH',unit:'Frac',value: '0.5771189'},//持水率water
					{key:'GH',unit:'Frac',value: '0.0064207'},//持气率gas
					{key:'RS',unit:'Mscf/ST3',value: '1.36927'},//溶解气油比率
				]
			}
		]
	}
]

const properties = {
    radiusTop: {
      name: 'radiusTop',
      value: 10,
      min: -40,
      max: 40,
      step: 1
    },
    radiusBottom: {
      name: 'radiusBottom',
      value: 20,
      min: -40,
      max: 40,
      step: 1
    },
    height: {
      name: 'height',
      value: 1000,
      min: 0,
      max: 1000,
      step: 1
    },
    segmentsX: {
      name: 'segmentsX',
      value: 8,
      min: 0,
      max: 40,
      step: 1
    },
    segmentsY: {
      name: 'segmentsY',
      value: 8,
      min: 0,
      max: 40,
      step: 1
    },
    openEnded: false
};


const colorList = [
	//卡其色
	'0xb69860',
	//浅黄
	'0xedd3a1',
	//枯色
	'0xe0c38c',
	//榛色
	'0xbfa46f',
	//樺茶色
	'0x726250',
	//朽葉色
	'0x917347',
	//路考茶
	'0x8c7042',
	'0x8c7042',
	//国防色
	'0x7b6c3e',
	'0x7b6c3e',
	//利休茶
	'0xa59564',
	//空五倍子色
	'0x9d896c',
	//生壁色
	'0x94846a',
	//肥後煤竹
	'0x897858',
	//媚茶
	'0x716246',
	//黄唐色
	'0xb98c46',
	//桑染
	'0xb79b5b',
	//黄橡
	'0xb68d4c',
	//芝翫茶
	'0xad7e4e',
	//狐色
	'0xc38743',
	//黄土色
	'0xc39143',
	//香染
	'0xad7d4c',
	//枇杷茶
	'0xae7c4f'
]

const colorsPalette = [
    {color:'0xff0f00', name:'1100'},
    {color:'0xff7d00', name:'1000'},
    {color:'0xffec00', name:'900'},
    {color:'0xa3ff00', name:'800'},
    {color:'0x00ff39', name:'700'},
    {color:'0x00ffa8', name:'600'},
    {color:'0x00e7ff', name:'500'},
    {color:'0x0078ff', name:'300'},
    {color:'0x000aff', name:'100'},
]

// 创建网格模型
function createMesh(x=0,y=0,z=0) {
    //创建圆柱
    //属性	必须	描述
    //radiusTop	否	该属性定义圆柱顶部圆的半径，默认值是20
    //radiusBottom	否	该属性定义圆柱底部圆的半径，默认值是20
    //height	否	该属性定义圆柱的高度，默认是100
    //segmentsX	否	该属性指定沿X轴分成多少段，段数越多，圆柱越光滑，默认值是8
    //segmentsY	否	该属性指定沿Y轴分成多少段，段数越多，圆柱竖直方向分的面越多，默认值是1
    //openEnded	否	该属性用来指定圆柱顶部和底部是否封闭，默认false

    const geom = new CylinderGeometry(
      properties.radiusTop.value,
      properties.radiusBottom.value,
      properties.height.value,
      properties.segmentsX.value,
      properties.segmentsY.value,
      properties.openEnded
    )
    // 创建材质
    const meshMaterial = new MeshNormalMaterial({
      side: DoubleSide
    })
    const wireFrameMat = new MeshBasicMaterial({ wireframe: true })

    // 添加组合材质
    let meshCyl = createMultiMaterialObject(geom, [
      meshMaterial,
      wireFrameMat
    ])

    meshCyl.position.set(x, y, z);

    return meshCyl;
}

function addsprite (color, text, postion) {
	let sprite = null
	let spriteMaterial = addspriteMaterial(color, text)
	sprite = new Sprite(spriteMaterial)
	sprite.scale.set(450, 150, 50) // 大小缩放比例
	// 在使用透视投影相机对象的时候，精灵模型对象显示的大小和网格模型一样受距离相机的距离影响，也就是距离越远，显示效果越小
	// 创建精灵模型对象，不需要几何体geometry参数
	// 更新材质
	sprite.material = spriteMaterial
	// 控制精灵大小，比如可视化中精灵大小表征数据大小 位置 只需要设置x、y两个分量就可以
	// 更新车辆标签位置
	sprite.position.set(postion.x, postion.y, postion.z)
	// 将geometry的groupsNeedUpdate属性设置为true来告知渲染器该对象需要更新
	sprite.geometry.groupsNeedUpdate = true
	return sprite
}

function addspriteMaterial (color, text) { 
	let texture = new Texture(createSpriteCanvas(color, text))
	texture.needsUpdate = true
	// 创建精灵材质对象SpriteMaterial 
	let spriteMaterial = new SpriteMaterial({
	  transparent: true,
	  map: texture // 设置精灵纹理贴图
	})
	return spriteMaterial
}

function createSpriteCanvas (color, text) {
	// 精灵平面（Sprite）是一个在3D场景中总是面对着相机的平面
	// 利用canvas绘制文字，作为sprite的材质 canvas 画布
	let canvas = document.createElement('canvas')
	// canvas 绘图上下文环境
	let context = canvas.getContext('2d')
	canvas.width = 120
	canvas.height = 40
	context.scale(2, 2)
	drawRect(context, color) // 绘制圆角矩形
	/* 字体颜色 */
	context.fillStyle = '#fff'
	// 减少阴影效果
	context.shadowColor = '#fff'
	context.shadowBlur = 1
	context.font = 'lighter 14px serif'
	/* 文字 */
	context.fillText(text, 1.9, 14.5)
	return canvas
}

function drawRect (ctx, color) {
	let width = 60
	let height = 20
	// 绘制一个圆角矩形
	strokeRoundRect(ctx, 1, 1, width - 2, height - 2, [2, 2, 2, 2], 1, color)
}

function strokeRoundRect (cxt, x, y, width, height, radius, lineWidth, strokeColor) {
	// 圆的直径必然要小于矩形的宽高
	if (2 * radius > width || 2 * radius > height) { return false }
	cxt.save()
	cxt.translate(x, y)
	// 绘制圆角矩形的各个边
	drawRoundRectPath(cxt, width, height, radius)
	cxt.lineWidth = lineWidth || 2 // 若是给定了值就用给定的值否则给予默认值2
	cxt.strokeStyle = strokeColor
	cxt.fillStyle = strokeColor + '88'
	cxt.fillRect(0, 0, width, height)
	cxt.stroke()
	cxt.restore()
}

function drawRoundRectPath (cxt, width, height, radius) {
	let r0 = radius[0]
	let r1 = radius[1]
	let r2 = radius[2]
	let r3 = radius[3]
	cxt.beginPath(0)
	// 从右下角顺时针绘制，弧度从0到1/2PI
	cxt.arc(width - r0, height - r0, r0, 0, Math.PI / 2)
	// 矩形下边线
	cxt.lineTo(r1, height)
	// 左下角圆弧，弧度从1/2PI到PI
	cxt.arc(r1, height - r1, r1, Math.PI / 2, Math.PI)
	// 矩形左边线
	cxt.lineTo(0, r2)
	// 左上角圆弧，弧度从PI到3/2PI
	cxt.arc(r2, r2, r2, Math.PI, Math.PI * 3 / 2)
	// 上边线
	cxt.lineTo(width - r3, 0)
	// 右上角圆弧
	cxt.arc(width - r3, r3, r3, Math.PI * 3 / 2, Math.PI * 2)
	// 右边线
	cxt.lineTo(width, height - r3)
	cxt.closePath()
}

function createBatchMesh(){
    wellInfo.map((item)=>{
        let { id, name, num, data, cpr } = item;
        let XCOORD = '0', YCOORD  = '0', DEPTH  = '0', STAGE  = '0';
        data[0].rest.map((it)=>{
            if(it.key==='XCOORD'){
                XCOORD = it.value
            }
            if(it.key==='YCOORD'){
                YCOORD = it.value
            }
            if(it.key==='DEPTH'){
                DEPTH = it.value
            }
            if(it.key==='STAGE'){
                STAGE = it.value
            }
        });
        
        // 位置矫正 补偿 XCOORD, YCOORD, DEPTH
        let x = ((XCOORD0/2000 + parseFloat(XCOORD))/1).toFixed(3);
        let y = 0; // = (parseInt(parseFloat)/50).toFixed(0);
        let z = ((YCOORD0/6000 + parseFloat(YCOORD))/1).toFixed(3);
        //console.log(x,y,z);
        x = x-4000;
        z = z+3000;
        let wellCyl = createMesh(x, y, z);
        wellCyl.name = "well_" + name;
        wellItems.add(wellCyl);

        let sprite = addsprite(cpr==='SHUT'?'#333333':'#00ff00', 
            name + '-' + cpr.substr(0, 2),
            {x: x, y: 550, z: z});
        sprite.name = "sprite_" + name;
        wellSprites.add(sprite);
        
    })

    // 油井 标牌 网格对象 批量添加到场景中
    scene.add(wellItems)
    scene.add(wellSprites);
}

function addBox(x=0,y=0,z=0){
    // 创建一个立方体
    const geometry = new BoxGeometry(80,80,80);
    const material = new MeshPhongMaterial({ color: 0x00ff00 });
    const cube = new Mesh(geometry, material);

	let cubeGeometry = new BoxGeometry(80, 80, 80);
    let cubeEdges = new EdgesGeometry(cubeGeometry, 1);
    let edgesMtl =  new LineBasicMaterial({color: 0xdd2222});
    edgesMtl.depthTest = true;// 深度测试，若开启则是边框透明的效果
    let cubeLine = new LineSegments(cubeEdges, edgesMtl);
    //将创建的线框加入的几何体中
    cube.add(cubeLine);

    cube.position.set(x, y, z);
    scene.add(cube);
}

function addSphere(x=0,y=0,z=0){
    // 创建球体几何体
     //radius（必需）：球体的半径。
     //widthSegments（可选）：水平方向的分段数，决定了球体的水平切片数。
     //heightSegments（可选）：垂直方向的分段数，决定了球体的纵向切片数。
     //phiStart（可选）：纵向起始角度，以弧度表示。
     //phiLength（可选）：纵向角度范围，以弧度表示。
     //thetaStart（可选）：水平起始角度，以弧度表示。
     //thetaLength（可选）：水平角度范围，以弧度表示。
     const radius = 50;
     const widthSegments = 32;
     const heightSegments = 16;
     const geometry = new SphereGeometry(radius, widthSegments, heightSegments);

     // 创建材质
     const material = new MeshBasicMaterial({ color: 0x0000ff });

     // 创建球体网格
     const sphere = new Mesh(geometry, material);
     sphere.position.set(x,y,z)
     scene.add(sphere); 
}

function isValidBufferGeometry(geometry) {
	if (!(geometry instanceof BufferGeometry)) {
	  return false;
	}
  
	const position = geometry.attributes.position;
	if (!position) {
	  return false;
	}
  
	// 检查顶点数组的长度是否合理
	if (position.count < 3) {
	  return false;
	}
  
	// 检查顶点数组是否包含正确的数据类型
	if (position.array.constructor !== Float32Array) {
	  return false;
	}
  
	// 可以继续检查其他属性，如法线、UV等
  
	return true;
  }
  
  function addColorBuffer(geometry){
	  // 使用函数检查几何体
	  const isValid = isValidBufferGeometry(geometry);
	  if(!isValid){
		  return
	  }
	  const pos = geometry.attributes.position;
	  const count = pos.count; //顶点数量
  
		  // 1. 计算模型y坐标高度差
	  const xArr = [];//顶点所有x坐标，也就是地形高度
	  const yArr = [];//顶点所有y坐标，也就是地形高度
	  const zArr = [];//顶点所有z坐标，也就是地形高度
	  for (let i = 0; i < count; i++) {
		  xArr.push(pos.getX(i));//获取顶点x坐标，也就是地形高度
		  yArr.push(pos.getY(i));//获取顶点y坐标，也就是地形高度
		  zArr.push(pos.getZ(i));//获取顶点z坐标，也就是地形高度
	  }
  
	  xArr.sort();//数组元素排序，从小到大
	  const minx = xArr[0];//x最小值
	  const maxx = xArr[xArr.length - 1];//x最大值
	  const xheight = maxx - minx; //山脉整体高度 
  
	  yArr.sort();//数组元素排序，从小到大
	  const miny = yArr[0];//y最小值
	  const maxy = yArr[yArr.length - 1];//y最大值
	  const yheight = maxy - miny; //山脉整体高度 
  
	  zArr.sort();//数组元素排序，从小到大
	  const minz = zArr[0];//z最小值
	  const maxz = zArr[zArr.length - 1];//z最大值
	  const zheight = maxz - minz; //山脉整体高度 
  
	  //console.log("x:",minx,maxx,xheight);
	  //console.log("y:",miny,maxy,yheight);
	  //console.log("z:",minz,maxz,zheight);
	  
	  // 计算每个顶点的颜色值 // 2. 计算每个顶点的颜色值
	  const colorsArr = [];
	  
	  // 根据顶点距离起点远近进行颜色插值计算
	  let c1 = new Color(parseInt(colorsPalette[8].color)); //曲线起点颜色 蓝色 山谷颜色
	  let c2 = new Color(parseInt(colorsPalette[0].color)); //曲线结束点颜色 红色 山顶颜色
	  for (let i = 0; i < count; i++) {
		  //const percent = i / count; //点索引值相对所有点数量的百分比
		  // 红色分量从0到1变化，蓝色分量从1到0变化
		  //colorsArr.push(percent, 0, 1 - percent); //蓝色到红色渐变色
		  //根据顶点位置顺序大小设置颜色渐变
		  //const c = c1.clone().lerp(c2, percent);//颜色插值计算
		  //const c = new Color();
		  //颜色插值结果，和c1一样rgb(1,0,0),50% c1 + 50% c2混合
		  //c.lerpColors(c1,c2, 0.5);
		  //colorsArr.push(c.r, c.g, c.b); 
  
		  //梯度(gradient)、散度(divergence)与旋度(rotation)
		  //梯度：标量求梯度得到矢量。
		  //散度：矢量求散度得到标量。
		  //旋度：矢量求旋度得到矢量。
  
		  //当前高度和整体高度比值
		  //const percent = (pos.getX(i) - minx) / xheight;
		  //const c = c1.clone().lerp(c2, percent);//颜色插值计算
		  //colorsArr.push(c.r, c.g, c.b); 
  
		  //ymax: 2845 
		  //ymin: 1750 
  
		  if(pos.getY(i)>=1700 && pos.getY(i)<2000 ){
			  c1 = new Color(parseInt(colorsPalette[8].color)); //曲线起点颜色 蓝色 山谷颜色
			  c2 = new Color(parseInt(colorsPalette[8].color)); //曲线结束点颜色 红色 山顶颜色
		  } else if(pos.getY(i)>=2000 && pos.getY(i)<2300 ){
			  c1 = new Color(parseInt(colorsPalette[7].color)); //曲线起点颜色 蓝色 山谷颜色
			  c2 = new Color(parseInt(colorsPalette[7].color)); //曲线结束点颜色 红色 山顶颜色
		  } else if(pos.getY(i)>=2300 && pos.getY(i)<2400 ){
			  c1 = new Color(parseInt(colorsPalette[6].color)); //曲线起点颜色 蓝色 山谷颜色
			  c2 = new Color(parseInt(colorsPalette[6].color)); //曲线结束点颜色 红色 山顶颜色
		  }  else if(pos.getY(i)>=2400 && pos.getY(i)<2500 ){
			  c1 = new Color(parseInt(colorsPalette[5].color)); //曲线起点颜色 蓝色 山谷颜色
			  c2 = new Color(parseInt(colorsPalette[5].color)); //曲线结束点颜色 红色 山顶颜色
		  }  else if(pos.getY(i)>=2500 && pos.getY(i)<2600 ){
			  c1 = new Color(parseInt(colorsPalette[4].color)); //曲线起点颜色 蓝色 山谷颜色
			  c2 = new Color(parseInt(colorsPalette[4].color)); //曲线结束点颜色 红色 山顶颜色
		  } else if(pos.getY(i)>=2600 && pos.getY(i)<2700 ){
			  c1 = new Color(parseInt(colorsPalette[3].color)); //曲线起点颜色 蓝色 山谷颜色
			  c2 = new Color(parseInt(colorsPalette[3].color)); //曲线结束点颜色 红色 山顶颜色
		  } else if(pos.getY(i)>=2700 && pos.getY(i)<2800 ){
			  c1 = new Color(parseInt(colorsPalette[2].color)); //曲线起点颜色 蓝色 山谷颜色
			  c2 = new Color(parseInt(colorsPalette[1].color)); //曲线结束点颜色 红色 山顶颜色
		  } else if(pos.getY(i)>=2800 && pos.getY(i)<2900 ){
			  c1 = new Color(parseInt(colorsPalette[1].color)); //曲线起点颜色 蓝色 山谷颜色
			  c2 = new Color(parseInt(colorsPalette[0].color)); //曲线结束点颜色 红色 山顶颜色
		  }
  
		  //console.log(pos.getY(i))
  
		  const percent = (pos.getY(i) - miny) / yheight;
		  const c = c1.clone().lerp(c2, percent);//颜色插值计算
		  colorsArr.push(c.r, c.g, c.b); 
  
		  //const percent = (pos.getZ(i) - minz) / zheight;
		  //const c = c1.clone().lerp(c2, percent);//颜色插值计算
		  //colorsArr.push(c.r, c.g, c.b); 
  
	  }
	  const colorBuffer = new Float32Array(colorsArr);
	  return colorBuffer
}

function updateMaterial( scene ) {
	const materialIndex = parseFloat( params.material );
	
	scene.traverse( c => {
		if ( c.isMesh ) {
			c.material.dispose();
			switch( materialIndex ) {
				case DEFAULT:
					c.material = c.originalMaterial;
					let colorCube1 = parseInt(colorList[0]);
					//let color1 = new Color(colorCube1);
					setTimeout(() => {
						const colorBuffer = addColorBuffer(c.geometry);
                        c.geometry.attributes.color = new BufferAttribute(colorBuffer, 3); 
					}, 1);
					c.material.vertexColors = true;//使用顶点颜色渲染

					//c.material.color = color1;
					c.material.side = DoubleSide;
					c.receiveShadow = false;
					c.castShadow = false;
					break;
				case GRADIENT:
					c.material = new ShaderMaterial( gradientShader );
					let colorCube2 = parseInt(colorList[1]);
					let color2 = new Color(colorCube2);
					c.material.color = color2;
					c.material.side = DoubleSide;
					c.receiveShadow = false;
					c.castShadow = false;
					break;
				case TOPOGRAPHIC_LINES:
					c.material = new ShaderMaterial( topoShader );
					let colorCube3 = parseInt(colorList[2]);
					let color3 = new Color(colorCube3);
					c.material.color = color3;
					c.material.side = DoubleSide;
					c.material.flatShading = true;
					c.receiveShadow = false;
					c.castShadow = false;
					break;
				case LIGHTING:
					c.material = new MeshStandardMaterial();
					let colorCube4 = parseInt(colorList[3]);
					let color4 = new Color(colorCube4);
					c.material.color = color4;
					c.material.side = DoubleSide;
					c.receiveShadow = true;
					c.castShadow = true;
					break;
				case GLASS:
					let colorCube5 = parseInt(colorList[4]);
					let color5 = new Color(colorCube5);
					const matParams = {
						color: color5,
						// 渲染两面
						side: DoubleSide,
						//wireframe: true, //材质的网格wireframe属性
						clearcoat: 1.0,//物体表面清漆层或者说透明涂层的厚度
						clearcoatRoughness: 0.1,//透明涂层表面的粗糙度
						transmission: 0.5,//物理材质透光率,模拟玻璃、半透明塑料一类的视觉效果,代替普通透明属性.opacity 设置Mesh透明度,即便完全透射的情况下仍可保持高反射率。
						ior: 1.5,//折射率.ior非金属材料的折射率从1.0到2.333。默认值为1.5。
						metalness: 0.9,//金属度
						roughness: 0.5,//粗糙度
						bumpScale: 0.5, // 凹凸贴图的高度
						envMapIntensity: 2.5, //环境贴图对Mesh表面影响程度
						opacity: 0.9,
						// 我们同样需要把tansparent属性打开
						transparent: true,
					}
					const glassMaterial = new MeshPhysicalMaterial(matParams);
					c.material = glassMaterial;
					c.material.side = DoubleSide;
					c.receiveShadow = true;
					c.castShadow = true;
					break;
				default:
				    break;

			}
		}

	} );

}


function reinstantiateTiles(url3Dtiles="") {

	//const  url3Dtiles = import.meta.env.BASE_URL + 'public/models/b3dmtest/test/' + 'tileset.json'
	// tiles
	//const url = window.location.hash.replace( /^#/, '' ) || + 'public/models/b3dmtest/test/' + 'tileset.json';
	//for(let i = 1; i < 33; i++){
	//	let  url3Dtiles1 = import.meta.env.BASE_URL + 'public/models/b3dmtest/'+ i + '00/tileset.json'
	//	setTimeout(function(){
			//reinstantiateTiles(url3Dtiles1);
	//	}, 1);
	//}

	url3Dtiles = import.meta.env.BASE_URL + 'public/models/b3dmtest/test/' + 'tileset.json'
	//url3Dtiles = import.meta.env.BASE_URL + 'public/models/b3dmtest/' + 'tileset.json'

	if ( tiles ) {
		geospatialRotationParent.remove( tiles.group );
		tiles.dispose();
	}

	tiles = new TilesRenderer(url3Dtiles);

	tiles.maxVisible = 3500;
	tiles.allowPicking = true;
	tiles.loadTilingScheme = true;

	/**/

	// 设置图层1的缓存大小
	tiles.lruCache.minSize = 1024;
	tiles.lruCache.maxSize = 10240;

	tiles.registerPlugin( new DebugTilesPlugin() );
	tiles.registerPlugin( new ImplicitTilingPlugin() );

	// Note the DRACO compression files need to be supplied via an explicit source.
	// We use unpkg here but in practice should be provided by the application.
	const dracoLoader = new DRACOLoader();
	dracoLoader.setDecoderPath( 'https://unpkg.com/three@0.153.0/examples/jsm/libs/draco/gltf/' );

	const ktx2loader = new KTX2Loader();
	ktx2loader.setTranscoderPath( 'https://unpkg.com/three@0.153.0/examples/jsm/libs/basis/' );
	ktx2loader.detectSupport( renderer );

	const loader = new GLTFLoader( tiles.manager );
	loader.setDRACOLoader( dracoLoader );
	loader.setKTX2Loader( ktx2loader );
	loader.register( () => new GLTFCesiumRTCExtension() );

	tiles.fetchOptions.mode = 'cors';
	tiles.manager.addHandler( /\.gltf$/, loader );
	//添加切片到三维场景
	geospatialRotationParent.add( tiles.group );

	//let tilesObj = tiles.group
	//scene.add( tilesObj )
	//tilesRendererArr.push(tiles)

	//WebGL 使用 OpenGL 惯例，其中 Y 轴朝上，Z 轴朝向观看者。WebGPU 使用 Metal 惯例，其中 Y 轴在屏幕之外，Z 轴在屏幕范围外。
	//请注意，在帧缓冲区坐标、视口坐标和片段/像素坐标中，Y 轴方向为向下。在剪辑空间中，Y 轴方向仍然与 WebGL 中的方向相同。
	//let x = -3850/1000, y = -1800/1000, z= -1750/1000,  sx = 0.001, sy = 0.001, sz = 0.001;
	// 几何体沿着x轴平移
	//tiles.group.translateX(x);
	// 几何体沿着y轴平移
	//tiles.group.translateY(y);
	// 几何体沿着Z轴平移
	//tiles.group.translateZ(z);

	// 修改模型的缩放
	//tiles.group.scale.set(sx, sy, sz); // 设置缩放比例 (x, y, z)
	// 几何体绕着x轴旋转90度
	//model.rotateZ(Math.PI);
	// 几何体绕着x轴旋转90度
	//tiles.group.rotateY(-Math.PI / 12);

	tiles.group.castShadow = true;
	
	tiles.addEventListener( 'load-tile-set', (tile) => {
		// optionally center the tile set in case it's far off center
		// 定位3dtiles
		//tile.tileSet.root.cached.materials = new MeshBasicMaterial({ color: 0xe91e63, side: DoubleSide });
		//tile.tileSet.root.cached.active = true;
		//console.log(tile.tileSet.root)
	});

	// Used with CUSTOM_COLOR
	tiles.customColorCallback = ( tile, object ) => {
		const depthIsEven = tile.__depth % 2 === 0;
		const hex = depthIsEven ? 0xff0000 : 0xffffff;
		object.traverse( child => {
			if ( child.isMesh && child.material ) {
				child.material.color.set( hex );
			}
		});
	};

	//本项目3dtiles数据格式,与osg2 cesiumApp和cesiumlab切片工具切出来的数据格式不同
	//const tilesRendererArr = []
	//const tilesetArr = res.root.children
    //for (const tilese of tilesetArr) {
      // console.log(qzpath + tilese.content.uri)
      //tilesRenderer = new TilesRenderer( qzpath + tilese.content.uri )
      //tilesRenderer.setCamera( camera )
      //tilesRenderer.setResolutionFromRenderer( camera, renderer )
      //const tilesObj = tilesRenderer.group
      //tilesObj.rotation.set(-Math.PI / 2, 0, 0)
      //scene.add( tilesObj )
      //tilesRendererArr.push(tilesRenderer)
    //}

	tiles.addEventListener( 'load-model', (tile) => {
		// optionally center the tile set in case it's far off center
		// 定位3dtiles
		//console.log(tile.scene.children[0])
		/*tile.scene.children.map( c => {
			if ( c.isMesh && c.material ) {

				c.originalMaterial = c.material;
				c.material = new MeshBasicMaterial({ color: 0xe91e63, side: DoubleSide });

				let colorCube = parseInt(colorList[0]);
				let color = new Color(colorCube);

				const matParams = {
					color: color,
					// 渲染两面
					side: DoubleSide,
					//wireframe: true, //材质的网格wireframe属性
					clearcoat: 1.0,//物体表面清漆层或者说透明涂层的厚度
					clearcoatRoughness: 0.1,//透明涂层表面的粗糙度
					transmission: 0.5,//物理材质透光率,模拟玻璃、半透明塑料一类的视觉效果,代替普通透明属性.opacity 设置Mesh透明度,即便完全透射的情况下仍可保持高反射率。
					ior: 1.5,//折射率.ior非金属材料的折射率从1.0到2.333。默认值为1.5。
					metalness: 0.9,//金属度
					roughness: 0.5,//粗糙度
					bumpScale: 0.5, // 凹凸贴图的高度
					envMapIntensity: 2.5, //环境贴图对Mesh表面影响程度
					opacity: 0.9,
					// 我们同样需要把tansparent属性打开
					transparent: true,
				}
				

				const glassMaterial = new MeshPhysicalMaterial(matParams);
				c.material = glassMaterial;

				//console.log(c.material)

			}
		});*/

		let tileScene = tile.scene
		tileScene.traverse( c => {
			if ( c.isMesh ) {
				c.originalMaterial = c.material;
			}
		} );
		updateMaterial( tileScene );
	});
	
	//scene.add( tiles.group );

	removeLoading();

}

function init() {

	addLoading();
	scene = new Scene();

	let dom = document.querySelector("#b3dtiles")

	// primary camera view
	renderer = new WebGLRenderer( { antialias: true } );
	renderer.setPixelRatio( window.devicePixelRatio );
	renderer.setSize( window.innerWidth, window.innerHeight );
	renderer.setClearColor( 0x151c1f );

	//document.body.appendChild( renderer.domElement );
	dom.appendChild( renderer.domElement );
	renderer.domElement.tabIndex = 1;

	let fov = 45; // 视野范围
    let aspect = window.innerWidth / window.innerHeight; // 相机默认值 画布的宽高比
    let near = 1; // 近平面
    let far = 20000; // 远平面
    // 透视投影相机
    camera = new PerspectiveCamera(fov, aspect, near, far);
	camera.position.set( -1000, 2000, -6000 );
	cameraHelper = new CameraHelper( camera );
	scene.add( cameraHelper );

	orthoCamera = new OrthographicCamera();
	orthoCameraHelper = new CameraHelper( orthoCamera );
	scene.add( orthoCameraHelper );

	// secondary camera view
	secondCamera = new PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 20000 );
	secondCamera.position.set( 3500, 3500, -3500 );
	secondCamera.lookAt( 0, 0, 0 );

	secondRenderer = new WebGLRenderer( { antialias: true } );
	secondRenderer.setPixelRatio( window.devicePixelRatio );
	secondRenderer.setSize( window.innerWidth, window.innerHeight );
	secondRenderer.setClearColor( 0x151c1f );

	dom.appendChild( secondRenderer.domElement );
	secondRenderer.domElement.style.position = 'absolute';
	secondRenderer.domElement.style.right = '0';
	secondRenderer.domElement.style.top = '0';
	secondRenderer.domElement.style.outline = '#0f1416 solid 2px';
	secondRenderer.domElement.tabIndex = 1;

	secondControls = new FlyOrbitControls( secondCamera, secondRenderer.domElement );
	secondControls.screenSpacePanning = false;
	secondControls.minDistance = 1;
	secondControls.maxDistance = 20000;

	secondCameraHelper = new CameraHelper( secondCamera );
	scene.add( secondCameraHelper );

	// Third person camera view
	thirdPersonCamera = new PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 20000 );
	thirdPersonCamera.position.set( 50, 40, 40 );
	thirdPersonCamera.lookAt( 0, 0, 0 );

	thirdPersonRenderer = new WebGLRenderer( { antialias: true } );
	thirdPersonRenderer.setPixelRatio( window.devicePixelRatio );
	thirdPersonRenderer.setSize( window.innerWidth, window.innerHeight );
	thirdPersonRenderer.setClearColor( 0x0f1416 );

	dom.appendChild( thirdPersonRenderer.domElement );
	thirdPersonRenderer.domElement.style.position = 'fixed';
	thirdPersonRenderer.domElement.style.left = '5px';
	thirdPersonRenderer.domElement.style.bottom = '5px';
	thirdPersonRenderer.domElement.tabIndex = 1;

	thirdPersonControls = new FlyOrbitControls( thirdPersonCamera, thirdPersonRenderer.domElement );
	thirdPersonControls.screenSpacePanning = false;
	thirdPersonControls.minDistance = 1;
	thirdPersonControls.maxDistance = 20000;

	// controls
	controls = new FlyOrbitControls( camera, renderer.domElement );
	controls.screenSpacePanning = false;
	controls.minDistance = 1;
	controls.maxDistance = 20000;

	// lights
	const dirLight = new DirectionalLight( 0xffffff, 2 );
	//dirLight.position.set( 1, 2, 3 );
	dirLight.position.set( 1000, 1000, 1000 );
	scene.add( dirLight );

	//const ambLight = new AmbientLight( 0xffffff, 0.2 );
	const ambLight = new AmbientLight( 0xffffff, 0.2 );
	ambLight.position.set( 0, 1000, 0 );
	scene.add( ambLight );

	const dirLight1 = new DirectionalLight( 0xffffff, 2 );
	//dirLight.position.set( 1, 2, 3 );
	dirLight1.position.set( 1000, -1000, 1000 );
	scene.add( dirLight1 );

	const dirLight2 = new DirectionalLight( 0xffffff, 2 );
	//dirLight.position.set( 1, 2, 3 );
	dirLight2.position.set( -1000, -1000, 1000 );
	scene.add( dirLight2 );

	const dirLight4 = new DirectionalLight( 0xffffff, 2 );
	//dirLight.position.set( 1, 2, 3 );
	dirLight4.position.set( -1000, -1000, -1000 );
	scene.add( dirLight4 );

	box = new Box3();
	sphere = new Sphere();

	offsetParent = new Group();
	scene.add( offsetParent );

	geospatialRotationParent = new Group();
	offsetParent.add( geospatialRotationParent );

	// Raycasting init
	raycaster = new Raycaster();
	mouse = new Vector2();

	rayIntersect = new Group();

	const rayIntersectMat = new MeshBasicMaterial( { color: 0xe91e63 } );
	const rayMesh = new Mesh( new CylinderGeometry( 0.25, 0.25, 6 ), rayIntersectMat );
	rayMesh.rotation.x = Math.PI / 2;
	rayMesh.position.z += 3;
	rayIntersect.add( rayMesh );

	const rayRing = new Mesh( new TorusGeometry( 1.5, 0.2, 16, 100 ), rayIntersectMat );
	rayIntersect.add( rayRing );
	scene.add( rayIntersect );
	rayIntersect.visible = false;

	reinstantiateTiles();

	onWindowResize();
	window.addEventListener( 'resize', onWindowResize, false );
	renderer.domElement.addEventListener( 'pointermove', onPointerMove, false );
	renderer.domElement.addEventListener( 'pointerdown', onPointerDown, false );
	renderer.domElement.addEventListener( 'pointerup', onPointerUp, false );
	renderer.domElement.addEventListener( 'pointerleave', onPointerLeave, false );

	secondRenderer.domElement.addEventListener( 'pointermove', onPointerMove, false );
	secondRenderer.domElement.addEventListener( 'pointerdown', onPointerDown, false );
	secondRenderer.domElement.addEventListener( 'pointerup', onPointerUp, false );
	secondRenderer.domElement.addEventListener( 'pointerleave', onPointerLeave, false );


	// GUI
	const gui = new GUI();
	gui.width = 300;

	const tileOptions = gui.addFolder( 'Tiles Options' );
	tileOptions.add( params, 'displayActiveTiles' );
	tileOptions.add( params, 'errorTarget' ).min( 0 ).max( 50 );
	tileOptions.add( params, 'errorThreshold' ).min( 0 ).max( 1000 );
	tileOptions.add( params, 'maxDepth' ).min( 1 ).max( 100 );
	tileOptions.add( params, 'up', [ '+Y', '+Z', '-Z' ] );
	tileOptions.open();

	const debug = gui.addFolder( 'Debug Options' );
	debug.add( params, 'displayBoxBounds' );
	debug.add( params, 'displaySphereBounds' );
	debug.add( params, 'displayRegionBounds' );
	debug.add( params, 'colorMode', {

		NONE,
		SCREEN_ERROR,
		GEOMETRIC_ERROR,
		DISTANCE,
		DEPTH,
		RELATIVE_DEPTH,
		IS_LEAF,
		RANDOM_COLOR,
		RANDOM_NODE_COLOR,
		CUSTOM_COLOR,
		LOAD_ORDER,

	} );
	debug.open();

	const exampleOptions = gui.addFolder( 'Example Options' );
	exampleOptions.add( params, 'resolutionScale' ).min( 0.01 ).max( 2.0 ).step( 0.01 ).onChange( onWindowResize );
	exampleOptions.add( params, 'orthographic' );
	exampleOptions.add( params, 'showThirdPerson' );
	exampleOptions.add( params, 'showSecondView' ).onChange( onWindowResize );
	exampleOptions.add( params, 'enableUpdate' ).onChange( v => {

		tiles.parseQueue.autoUpdate = v;
		tiles.downloadQueue.autoUpdate = v;

		if ( v ) {

			tiles.parseQueue.scheduleJobRun();
			tiles.downloadQueue.scheduleJobRun();

		}

	} );
	exampleOptions.add( params, 'raycast', { NONE, ALL_HITS, FIRST_HIT_ONLY } );
	exampleOptions.add( params, 'optimizeRaycast', );
	exampleOptions.add( params, 'enableCacheDisplay' );
	exampleOptions.add( params, 'enableRendererStats' );
	exampleOptions.open();

	
	gui.add( params, 'material', { DEFAULT, GRADIENT, TOPOGRAPHIC_LINES, LIGHTING, GLASS } )
		.onChange( () => {
			tiles.forEachLoadedModel( updateMaterial )
		});
	gui.add( params, 'reload' );
	//gui.open();
	gui.close();

	statsContainer = document.createElement( 'div' );
	statsContainer.style.position = 'absolute';
	statsContainer.style.top = 0;
	statsContainer.style.left = 0;
	statsContainer.style.color = 'white';
	statsContainer.style.width = '100%';
	statsContainer.style.textAlign = 'center';
	statsContainer.style.padding = '5px';
	statsContainer.style.pointerEvents = 'none';
	statsContainer.style.lineHeight = '1.5em';
	dom.appendChild( statsContainer );

	// Stats
	stats = new Stats();
	stats.showPanel( 0 );
	stats.dom.style.display = 'none'
	dom.appendChild( stats.dom );

	const geometry = new BoxGeometry(100, 100, 100);
	const material = new MeshPhongMaterial({
		color: 0xff0000
	});
	const cube = new Mesh(geometry, material);
	cube.position.set(0, 350, 0);
	scene.add(cube);

	createBatchMesh();

	let wellTemp = createMesh(0,100,0);
	wellTemp.name = "wellTemp";
	scene.add(wellTemp);
  
	addBox(0,500,0);
	addSphere(0,500,0);

	animate();


}

function onWindowResize() {

	thirdPersonCamera.aspect = window.innerWidth / window.innerHeight;
	thirdPersonCamera.updateProjectionMatrix();
	thirdPersonRenderer.setSize( Math.floor( window.innerWidth / 3 ), Math.floor( window.innerHeight / 3 ) );

	if ( params.showSecondView ) {

		camera.aspect = 0.5 * window.innerWidth / window.innerHeight;
		renderer.setSize( 0.5 * window.innerWidth, window.innerHeight );

		secondCamera.aspect = 0.5 * window.innerWidth / window.innerHeight;
		secondRenderer.setSize( 0.5 * window.innerWidth, window.innerHeight );
		secondRenderer.domElement.style.display = 'block';

	} else {

		camera.aspect = window.innerWidth / window.innerHeight;
		renderer.setSize( window.innerWidth, window.innerHeight );

		secondRenderer.domElement.style.display = 'none';

	}
	camera.updateProjectionMatrix();
	renderer.setPixelRatio( window.devicePixelRatio * params.resolutionScale );

	secondCamera.updateProjectionMatrix();
	secondRenderer.setPixelRatio( window.devicePixelRatio );

	updateOrthoCamera();

}

function onPointerLeave( e ) {

	lastHoveredElement = null;

}

function onPointerMove( e ) {

	const bounds = this.getBoundingClientRect();
	mouse.x = e.clientX - bounds.x;
	mouse.y = e.clientY - bounds.y;
	mouse.x = ( mouse.x / bounds.width ) * 2 - 1;
	mouse.y = - ( mouse.y / bounds.height ) * 2 + 1;

	lastHoveredElement = this;

}

const startPos = new Vector2();
const endPos = new Vector2();
function onPointerDown( e ) {

	const bounds = this.getBoundingClientRect();
	startPos.set( e.clientX - bounds.x, e.clientY - bounds.y );

}

function onPointerUp( e ) {

	const bounds = this.getBoundingClientRect();
	endPos.set( e.clientX - bounds.x, e.clientY - bounds.y );
	if ( startPos.distanceTo( endPos ) > 2 ) {

		return;

	}

	if ( lastHoveredElement === secondRenderer.domElement ) {

		raycaster.setFromCamera( mouse, secondCamera );

	} else {

		raycaster.setFromCamera( mouse, params.orthographic ? orthoCamera : camera );

	}

	raycaster.firstHitOnly = true;
	const results = raycaster.intersectObject( tiles.group, true );
	if ( results.length ) {

		const object = results[ 0 ].object;
		const info = tiles.getPluginByName( 'DEBUG_TILES_PLUGIN' ).getTileInformationFromActiveObject( object );

		let str = '';
		for ( const key in info ) {

			let val = info[ key ];
			if ( typeof val === 'number' ) {

				val = Math.floor( val * 1e5 ) / 1e5;

			}

			let name = key;
			while ( name.length < 20 ) {

				name += ' ';

			}

			str += `${ name } : ${ val }\n`;

		}
		console.log( str );

	}

}

function updateOrthoCamera() {

	orthoCamera.position.copy( camera.position );
	orthoCamera.rotation.copy( camera.rotation );

	const scale = camera.position.distanceTo( controls.target ) / 2.0;
	let aspect = window.innerWidth / window.innerHeight;
	if ( params.showSecondView ) {

		aspect *= 0.5;

	}
	orthoCamera.left = - aspect * scale;
	orthoCamera.right = aspect * scale;
	orthoCamera.bottom = - scale;
	orthoCamera.top = scale;
	orthoCamera.near = camera.near;
	orthoCamera.far = camera.far;
	orthoCamera.updateProjectionMatrix();

}

function animate() {

	requestAnimationFrame( animate );

	// update options
	tiles.errorTarget = params.errorTarget;
	tiles.errorThreshold = params.errorThreshold;
	tiles.optimizeRaycast = params.optimizeRaycast;
	tiles.displayActiveTiles = params.displayActiveTiles;
	tiles.maxDepth = params.maxDepth;

	// update plugin
	const plugin = tiles.getPluginByName( 'DEBUG_TILES_PLUGIN' );
	plugin.displayBoxBounds = params.displayBoxBounds;
	plugin.displaySphereBounds = params.displaySphereBounds;
	plugin.displayRegionBounds = params.displayRegionBounds;
	plugin.colorMode = parseFloat( params.colorMode );

	if ( params.orthographic ) {

		tiles.deleteCamera( camera );
		tiles.setCamera( orthoCamera );
		tiles.setResolutionFromRenderer( orthoCamera, renderer );

	} else {

		tiles.deleteCamera( orthoCamera );
		tiles.setCamera( camera );
		tiles.setResolutionFromRenderer( camera, renderer );

	}

	if ( params.showSecondView ) {

		tiles.setCamera( secondCamera );
		tiles.setResolutionFromRenderer( secondCamera, secondRenderer );

	} else {

		tiles.deleteCamera( secondCamera );

	}

	if ( tiles.root && tiles.root.boundingVolume.region ) {

		tiles.getOrientedBoundingBox( box, geospatialRotationParent.matrix );
		geospatialRotationParent.matrix.decompose( geospatialRotationParent.position, geospatialRotationParent.quaternion, geospatialRotationParent.scale );
		geospatialRotationParent.position.set( 0, 0, 0 );
		geospatialRotationParent.quaternion.invert();
		geospatialRotationParent.scale.set( 1, 1, 1 );

	}

	offsetParent.rotation.set( 0, 0, 0 );
	if ( params.up === '-Z' ) {

		offsetParent.rotation.x = Math.PI / 2;

	} else if ( params.up === '+Z' ) {

		offsetParent.rotation.x = - Math.PI / 2;

	}

	offsetParent.updateMatrixWorld( false );

	// update tiles center
	if ( tiles.getBoundingBox( box ) ) {

		box.getCenter( tiles.group.position );
		tiles.group.position.multiplyScalar( - 1 );

	} else if ( tiles.getBoundingSphere( sphere ) ) {

		tiles.group.position.copy( sphere.center );
		tiles.group.position.multiplyScalar( - 1 );

	}

	if ( parseFloat( params.raycast ) !== NONE && lastHoveredElement !== null ) {

		if ( lastHoveredElement === renderer.domElement ) {

			raycaster.setFromCamera( mouse, params.orthographic ? orthoCamera : camera );

		} else {

			raycaster.setFromCamera( mouse, secondCamera );

		}

		raycaster.firstHitOnly = parseFloat( params.raycast ) === FIRST_HIT_ONLY;

		const results = raycaster.intersectObject( tiles.group, true );
		if ( results.length ) {

			const closestHit = results[ 0 ];
			const point = closestHit.point;
			rayIntersect.position.copy( point );

			// If the display bounds are visible they get intersected
			if ( closestHit.face ) {

				const normal = closestHit.face.normal;
				normal.transformDirection( closestHit.object.matrixWorld );
				rayIntersect.lookAt(
					point.x + normal.x,
					point.y + normal.y,
					point.z + normal.z
				);

			}

			rayIntersect.visible = true;

		} else {

			rayIntersect.visible = false;

		}

	} else {

		rayIntersect.visible = false;

	}

	// update tiles
	//window.tiles = tiles;
	if ( params.enableUpdate ) {

		secondCamera.updateMatrixWorld();
		camera.updateMatrixWorld();
		orthoCamera.updateMatrixWorld();
		tiles.update();

	}

	//if(tilesRendererArr.length){
	//	for (const tilesRenderer of tilesRendererArr) {
	//		tilesRenderer.update()
	//	}
	//}

	render();
	stats.update();

}

function render() {

	updateOrthoCamera();

	cameraHelper.visible = false;
	orthoCameraHelper.visible = false;
	secondCameraHelper.visible = false;

	// render primary view
	if ( params.orthographic ) {

		const dist = orthoCamera.position.distanceTo( rayIntersect.position );
		rayIntersect.scale.setScalar( dist / 150 );

	} else {

		const dist = camera.position.distanceTo( rayIntersect.position );
		rayIntersect.scale.setScalar( dist * camera.fov / 6000 );

	}
	renderer.render( scene, params.orthographic ? orthoCamera : camera );

	// render secondary view
	if ( params.showSecondView ) {

		const dist = secondCamera.position.distanceTo( rayIntersect.position );
		rayIntersect.scale.setScalar( dist * secondCamera.fov / 6000 );
		secondRenderer.render( scene, secondCamera );

	}

	// render third person view
	thirdPersonRenderer.domElement.style.visibility = params.showThirdPerson ? 'visible' : 'hidden';
	if ( params.showThirdPerson ) {

		cameraHelper.update();
		cameraHelper.visible = ! params.orthographic;

		orthoCameraHelper.update();
		orthoCameraHelper.visible = params.orthographic;

		if ( params.showSecondView ) {

			secondCameraHelper.update();
			secondCameraHelper.visible = true;

		}

		const dist = thirdPersonCamera.position.distanceTo( rayIntersect.position );
		rayIntersect.scale.setScalar( dist * thirdPersonCamera.fov / 6000 );
		thirdPersonRenderer.render( scene, thirdPersonCamera );

	}

	const cacheFullness = tiles.lruCache.itemList.length / tiles.lruCache.maxSize;
	let str = `Downloading: ${ tiles.stats.downloading } Parsing: ${ tiles.stats.parsing } Visible: ${ tiles.visibleTiles.size }`;

	if ( params.enableCacheDisplay ) {

		const geomSet = new Set();
		tiles.traverse( tile => {
			const scene = tile.cached.scene;
			if ( scene ) {
				scene.traverse( c => {
					if ( c.geometry ) {
						geomSet.add( c.geometry );
						console.log( c.geometry )
					}
				});
			}
		} );

		let count = 0;
		geomSet.forEach( g => {

			count += BufferGeometryUtils.estimateBytesUsed( g );

		} );
		str += `<br/>Cache: ${ ( 100 * cacheFullness ).toFixed( 2 ) }% ~${ ( count / 1000 / 1000 ).toFixed( 2 ) }mb`;

	}

	if ( params.enableRendererStats ) {

		const memory = renderer.info.memory;
		const programCount = renderer.info.programs.length;
		str += `<br/>Geometries: ${ memory.geometries } Textures: ${ memory.textures } Programs: ${ programCount }`;

	}

	if ( statsContainer.innerHTML !== str ) {

		statsContainer.innerHTML = str;

	}

}


export { init };
